/*加载依赖*/
var gulp = require('gulp'); //导入gulp模块
var uglify = require('gulp-uglify'); //压缩、丑化js
var minify = require('gulp-minify-css'); //压缩css
var imagemin = require('gulp-imagemin'); //压缩图片
var htmlmin = require('gulp-htmlmin'); //压缩html
var sass = require('gulp-sass'); //编译sass
var rename = require('gulp-rename'); //文件重命名
var browser = require('browser-sync').create(); //本地服务器
var reload = browser.reload; //重载页面
var plumber = require('gulp-plumber'); //html,js语法检查

/*创建任务*/
//搭建服务器
gulp.task('serve', ['uglify', 'minify', 'htmlmin', 'imagemin'], function() {
	browser.init({
		server: 'dist',
		port: '8088',
		index: 'index.html'
	})

	gulp.watch('src/js/**/*.js', ['uglify'])
	gulp.watch('src/sass/**/*.scss', ['minify'])
	gulp.watch('src/**/*.html', ['htmlmin'])
	gulp.watch('src/images/**/*.*', ['imagemin'])
})

//1.压缩、丑化js
gulp.task('uglify', function() {
		gulp.src('src/js/**/*.js') //找到源文件
			.pipe(plumber()) //检查语法
			.pipe(uglify()) //压缩、丑化
			.pipe(rename({
				suffix: '.min'
			}))
			.pipe(gulp.dest('dist/js')) //输出
			.pipe(reload({
				stream: true
			}))
	})
	//2.编译sass
gulp.task('sass', function() {
		gulp.src('src/sass/**/*.scss')
			.pipe(sass().on('error', sass.logError))
			.pipe(gulp.dest('src/css'))
			.pipe(reload({
				stream: true
			}))
	})
	//3.压缩css
gulp.task('minify', ['sass'], function() {
		gulp.src('src/css/**/*.css')
			.pipe(minify())
			.pipe(rename({
				suffix: '.min'
			}))
			.pipe(gulp.dest('dist/css'))
			.pipe(reload({
				stream: true
			}))
	})
	//4.压缩html
gulp.task('htmlmin', function() {
		var options = {
			removeComments: true, //清除HTML注释
			collapseWhitespace: true, //压缩HTML
			collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input checked/>
			removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
			removeScriptTypeAttributes: false, //删除<script>的type="text/javascript"
			removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
			minifyJS: true, //压缩页面JS
			minifyCSS: true //压缩页面CSS
		};
		gulp.src('src/**/*.html')
			.pipe(plumber())
			.pipe(htmlmin(options))
			.pipe(gulp.dest('dist'))
			.pipe(reload({
				stream: true
			}))
	})
	//5.压缩图片
gulp.task('imagemin', function() {
	gulp.src('src/images/**/*.*')
		.pipe(imagemin())
		.pipe(gulp.dest('dist/images'))
})

//默认任务
gulp.task('default', ['serve'])